const { execSync } = require('child_process');
const os = require('os');
const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: '请输入你要杀死的端口: '
});


rl.question('请输入你要杀死的端口: ', (portInput) => {
  const port = parseInt(portInput, 10);
  if (isNaN(port) || port < 1 || port > 65535) {
    console.log('请输入有效的端口号（1-65535）');
    rl.close();
    return;
  }

  // 获取操作系统类型
  const isWindows = os.type() === 'Windows_NT';

  try {
    console.log(`Attempting to find and kill processes using port ${port}...`);

    let command;
    if (isWindows) {
      command = `netstat -ano | findstr :${port}`;
    } else {
      command = `lsof -i :${port}`;
    }

    const result = execSync(command).toString();
    if (result.trim() === '') {
      console.log(`No process is using port ${port}.`);
      process.exit(0);
    }

    let pids = [];
    if (isWindows) {
      const lines = result.split('\n');
      for (const line of lines) {
        if (line.includes(':') && (line.includes('LISTENING') || line.includes('ESTABLISHED'))) {
          const match = line.match(/\s(\d+)\s$/);
          if (match) {
            const pid = match[1];
            if (pid && !isNaN(pid)) {
              pids.push(pid);
            }
          }
        }
      }
    } else {
      const lines = result.split('\n');
      for (const line of lines) {
        if (!line.startsWith('COMMAND')) {
          const parts = line.split(/\s+/);
          const pid = parts[1];
          if (pid && !isNaN(pid)) {
            pids.push(pid);
          }
        }
      }
    }

    if (pids.length === 0) {
      console.log(`No process is using port ${port}.`);
      process.exit(0);
    }

    console.log(`Found processes using port ${port}: ${pids.join(', ')}`);
    console.log('Attempting to kill these processes...');

    pids.forEach(pid => {
      try {
        if (isWindows) {
          execSync(`taskkill /PID ${pid} /F`);
        } else {
          execSync(`kill -9 ${pid}`);
        }
        console.log(`Successfully killed process with PID: ${pid}`);
      } catch (error) {
        console.error(`Failed to kill process with PID ${pid}: ${error.message}`);
      }
    });

  } catch (error) {
    console.error(`Error: ${error.message}`);
    console.log('If you are on Windows, try running this script as Administrator.');
    process.exit(1);
  }
  rl.close();
});